﻿#region
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Windows.Forms;
using Y2M.Components;

#endregion

namespace Y2M.Controls
{
    [DefaultEvent("CommandExecuted")]
    public partial class ClipListControl : UserControl
    {
        public ClipListControl()
        {
            InitializeComponent();

            if (DesignMode || RunTimeChecker.IsRunTime == false)
                return;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (DesignMode || RunTimeChecker.IsRunTime == false)
                return;

            cbbNumberPerPage.SelectedIndex = 1;
            cbbNumberPerPage.SelectedIndexChanged += cbbNumberPerPage_SelectedIndexChanged;
        }

        #region thumbnail job
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<ClipControl> clipControls = (List<ClipControl>) e.Argument;

            WebClient webClient = new WebClient();
            foreach (var clipControl in clipControls)
            {
                var thumbnail = ThumbnailDictionary.Instance[clipControl.Clip.ThumbnailUrl];

                if (thumbnail == null)
                {
                    thumbnail = webClient.DownloadData(clipControl.Clip.ThumbnailUrl);
                    ThumbnailDictionary.Instance.Add(clipControl.Clip.ThumbnailUrl, thumbnail);
                }

                clipControl.Clip.Thumbnail = thumbnail;

                ((BackgroundWorker) sender).ReportProgress(0, clipControl);
            }
        }

        private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ClipControl clipControl = (ClipControl) e.UserState;
            clipControl.LoadThumbnail();
        }
        #endregion

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Enabled = false;

            int rowsPerPage = Convert.ToInt32(cbbNumberPerPage.Text);
            int toalCount;
            var list = YoutubeHelper.Search(txeSearch.Text, uscPager.StartRowIndex + 1, rowsPerPage, out toalCount);

            // 유튜브에서 지원하는 최대값
            if (toalCount > 1000)
                toalCount = 1000;

            uscPager.Initialize(toalCount, rowsPerPage);

            LoadClips(list);

            Enabled = true;
        }

        private void LoadClips(ClipList list)
        {
            foreach (ClipControl control in pnlClip.Controls)
                control.CommandExecuted -= ClipControl_CommandExecuted;
            pnlClip.Controls.Clear();

            List<ClipControl> clipControls = new List<ClipControl>(list.Count);

            foreach (var clip in list)
            {
                ClipControl clipControl = new ClipControl(clip);
                clipControl.Height = 96;
                clipControl.Dock = DockStyle.Top;
                clipControl.CommandExecuted += ClipControl_CommandExecuted;
                clipControls.Add(clipControl);
            }
            clipControls.Reverse();
            pnlClip.Controls.AddRange(clipControls.ToArray());

            clipControls.Reverse();
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += Worker_DoWork;
            worker.ProgressChanged += Worker_ProgressChanged;
            worker.RunWorkerAsync(clipControls);

            pnlClip.Focus();
        }

        private void ClipControl_CommandExecuted(object sender, ClipControl.CommandExecutedEventArgs e)
        {
            OnCommandExecuted(e.Command, e.Clip);
        }

        private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnSearch.PerformClick();
        }

        private void cbbNumberPerPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnSearch.PerformClick();
        }

        private void uscPager_Paged(object sender, DataPager.PagedEventArgs e)
        {
            int rowsPerPage = Convert.ToInt32(cbbNumberPerPage.Text);
            int toalCount;
            var list = YoutubeHelper.Search(txeSearch.Text, uscPager.StartRowIndex + 1, rowsPerPage, out toalCount);

            LoadClips(list);
        }

        #region CommandExecuted event things for C# 3.0
        public event EventHandler<CommandExecutedEventArgs> CommandExecuted;

        protected virtual void OnCommandExecuted(CommandExecutedEventArgs e)
        {
            if (CommandExecuted != null)
                CommandExecuted(this, e);
        }

        protected virtual void OnCommandExecuted(ClipCommand command, Clip clip)
        {
            OnCommandExecuted(new CommandExecutedEventArgs(command, clip));
        }

        protected virtual CommandExecutedEventArgs OnCommandExecutedWithReturn(ClipCommand command, Clip clip)
        {
            CommandExecutedEventArgs args = new CommandExecutedEventArgs(command, clip);
            OnCommandExecuted(args);

            return args;
        }

        public class CommandExecutedEventArgs : EventArgs
        {
            public ClipCommand Command { get; set; }
            public Clip Clip { get; set; }

            public CommandExecutedEventArgs()
            {
            }

            public CommandExecutedEventArgs(ClipCommand command, Clip clip)
            {
                Command = command;
                Clip = clip;
            }
        }
        #endregion
    }
}